import java.util.ArrayList;
import java.util.Arrays;

public class merge {
    public static int[][] sort(int[][] intervals){
        if(intervals.length < 2 || intervals == null){
            return intervals;
        }
        ArrayList<int[]> result = new ArrayList<>();
        Arrays.sort(intervals,(a,b)->a[0]-b[0]);
        for(int[] interval : intervals){
            if(result.size() == 0 || interval[0] > result.get(result.size()-1)[0]){
                result.add(interval);
            }else {
                result.get(result.size()-1)[0] = Math.max(interval[1],result.get(result.size()-1)[1]);
            }
        }
        return result.toArray(new int[result.size()][2]);
    }

    public static void main(String[] args) {
        int[][] nums = {{1,6},{8,10},{15,18}};
        int[][] result = sort(nums);
        System.out.println(Arrays.deepToString(result));
    }
}
